package com.mikelouis.test.scala.proginscala.chapter28

/**
 * These equals methods are not symmetric.
 * Sometimes p.equals(cp) but not cp.equals(p)
 * Created by yuazhu on 2/26/2015.
 */
object Points5 {

  class Point(var x: Int, var y: Int) {
    // Problematic
    override def hashCode = 41 * (41 + x) + y

    override def equals(other: Any) = other match {
      case that: Point => this.x == that.x && this.y == that.y
      case _ => false
    }
  }

  object Color extends Enumeration {
    val Red, Orange, Yellow, Green, Blue, Indigo, Violet = Value
  }

  class ColoredPoint(x: Int, y: Int, val color: Color.Value)
    extends Point(x, y) {
    // Problem: equals not symmetric

    override def equals(other: Any) = other match {
      case that: ColoredPoint =>
        this.color == that.color && super.equals(that)
      case _ => false
    }
  }

  def main(args: Array[String]) {
    val p = new Point(1, 2)
    val cp = new ColoredPoint(1, 2, Color.Red)
    println(p equals cp)
    println(cp equals p)

    // side effect of this issue
    println(scala.collection.mutable.HashSet[Point](p) contains cp)
    println(scala.collection.mutable.HashSet[Point](cp) contains p)
  }

}
